const express = require('express');
const router = express.Router();
const { sequelize, User } = require('../../models');
const { success, failure } = require('../../utils/responses');
const { BadRequest } = require('http-errors');
const { initOrderStream, broadcastOrderCount } = require('../../streams/count-order');
/**
 * 统计用户性别
 * GET /admin/charts/sex
 */
router.get('/sex', async (req, res) => {
  try {
    const [male, female, unknown] = await Promise.all([
      User.count({ where: { sex: 0 } }),
      User.count({ where: { sex: 1 } }),
      User.count({ where: { sex: 2 } }),
    ]);
    const data = [
      { value: male, name: '男性' },
      { value: female, name: '女性' },
      { value: unknown, name: '未选择' },
    ];
    success(res, '查询用户性别成功。', { data });
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 统计用户数量
 * GET /admin/charts/user
 */
// router.get("/user", async (req, res) => {
//   try {
//     let { type, yearMonth } = req.query;

//     const [results] = await sequelize.query(
//       "SELECT DATE_FORMAT(`createdAt`, '%Y-%m') AS `month`, COUNT(*) AS `value` FROM `Users` GROUP BY `month` ORDER BY `month` ASC"
//     );

//     const data = {
//       months: [],
//       values: [],
//     };

//     results.forEach((item) => {
//       data.months.push(item.month);
//       data.values.push(item.value);
//     });
//     success(res, "查询每月用户数量成功。", { data });
//   } catch (error) {
//     failure(res, error);
//   }
// });

/**
 * 统计用户数量
 * GET /admin/charts/user
 */
router.get('/user', async (req, res) => {
  try {
    let { type = 'year', yearMonth } = req.query;

    // 参数验证
    if (!yearMonth) {
      throw new BadRequest('请提供 yearMonth 参数');
    }

    let sql, results;

    if (type === 'month') {
      // 按月统计：查询指定月份每天的用户数量
      const [year, month] = yearMonth.split('-');
      if (!year || !month) {
        throw new BadRequest('yearMonth 参数格式错误，应为 YYYY-MM');
      }

      // 验证月份是否在有效范围内
      const monthNum = parseInt(month);
      if (monthNum < 1 || monthNum > 12) {
        throw new BadRequest('月份必须在 1-12 之间');
      }

      sql = `
        SELECT 
          DATE_FORMAT(\`createdAt\`, '%Y-%m-%d') AS \`date\`, 
          COUNT(*) AS \`value\` 
        FROM \`Users\` 
        WHERE 
          YEAR(\`createdAt\`) = ? 
          AND MONTH(\`createdAt\`) = ?
        GROUP BY \`date\` 
        ORDER BY \`date\` ASC
      `;
      [results] = await sequelize.query(sql, {
        replacements: [year, month],
      });
    } else if (type === 'year') {
      // 按年统计：查询指定年份每月的用户数量
      const year = yearMonth.split('-')[0];
      if (!year) {
        throw new BadRequest('yearMonth 参数格式错误，应为 YYYY 或 YYYY-MM');
      }

      sql = `
        SELECT 
          DATE_FORMAT(\`createdAt\`, '%Y-%m') AS \`month\`, 
          COUNT(*) AS \`value\` 
        FROM \`Users\` 
        WHERE YEAR(\`createdAt\`) = ?
        GROUP BY \`month\` 
        ORDER BY \`month\` ASC
      `;
      [results] = await sequelize.query(sql, {
        replacements: [year],
      });
    } else {
      throw new BadRequest('type 参数错误，应为 month 或 year');
    }

    // 处理返回数据
    const data = {
      labels: [],
      values: [],
      total: 0,
    };

    results.forEach((item) => {
      const label = type === 'month' ? item.date : item.month;
      data.labels.push(label);
      data.values.push(item.value);
      data.total += item.value;
    });

    // 如果是按月统计，确保返回完整的一个月数据（包括没有用户的日期）
    if (type === 'month') {
      data.labels = await generateFullMonthLabels(yearMonth, data.labels);
      data.values = await generateFullMonthValues(data.labels, results);
    }

    success(res, `查询${type === 'month' ? '每日' : '每月'}用户数量成功。`, {
      data,
      query: { type, yearMonth },
    });
  } catch (error) {
    console.error('统计用户数量错误:', error);
    failure(res, error);
  }
});


/**
 * SSE 统计每个月订单数量
 * GET /admin/charts/stream_order
 */
router.get('/stream_order', async (req, res) => {
  try {
    initOrderStream(res, req);
    await broadcastOrderCount(); // 可以单独写个接口获取初始数据，可以避免当有用户连接时向其他用户推送数据
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 生成完整月份的所有日期标签
 */
async function generateFullMonthLabels(yearMonth, existingLabels) {
  const [year, month] = yearMonth.split('-');
  const daysInMonth = new Date(year, month, 0).getDate(); // 获取当月天数

  const fullLabels = [];
  for (let day = 1; day <= daysInMonth; day++) {
    const dateStr = `${year}-${month.padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    fullLabels.push(dateStr);
  }

  return fullLabels;
}

/**
 * 生成完整月份的用户数量数据（包括没有用户的日期填0）
 */
async function generateFullMonthValues(fullLabels, results) {
  const valueMap = {};

  // 将查询结果转换为映射
  results.forEach((item) => {
    valueMap[item.date] = item.value;
  });

  // 生成完整的数据数组
  const fullValues = fullLabels.map((label) => {
    return valueMap[label] || 0;
  });

  return fullValues;
}
module.exports = router;
